package com.hskn.hss.module.voiceIntercom.controller;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.module.grid.To.GridTo;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.mapper.UserMapper;
import com.hskn.hss.module.user.service.IUserService;
import com.hskn.hss.module.voiceIntercom.entity.UserAvatar;
import com.hskn.hss.module.voiceIntercom.entity.UserAvatarTo;
import com.hskn.hss.module.voiceIntercomGroup.entity.VoiceIntercomGroup;
import com.hskn.hss.module.voiceIntercomGroup.mapper.VoiceIntercomGroupMapper;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.Tools;
import com.tencentyun.TLSSigAPIv2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-17
 */
@Api(tags = {"-voiceIntercom"}, description = "语音对讲")
@Slf4j
@RestController
@RequestMapping("/hss/voiceIntercom")
public class VoiceIntercomController {

    @Value("${trtc.sdkAppid}")
    private int sdkAppid;

    @Value("${trtc.sdkAppkey}")
    private String sdkAppkey;

    @Resource
    private VoiceIntercomGroupMapper voiceIntercomGroupMapper;

    @Autowired
    private IUserService userService;

    @Resource
    private UserMapper userMapper;


    @ApiOperation(value = "获取UserSig接口", notes = "获取UserSig")
    @RequestMapping(value = "getUserSig", method = RequestMethod.POST)
    public AjaxResult<Object> getUserSig(HttpServletRequest request) {

        JSONObject params = JSON.parseObject(Tools.getBody(request));
        String userId = params.getString("userId");

        if (StringUtils.isEmpty(userId)){
            userId = LoginUtils.getUser().getUid();
        }

        TLSSigAPIv2 api = new TLSSigAPIv2(sdkAppid, sdkAppkey);
        String userSig = api.genUserSig(userId, 180 * 86400);

        Map map = new HashMap();
        map.put("userId",userId);
        map.put("sdkAppid",sdkAppid);
        map.put("userSig",userSig);

        System.out.print(userSig);
        return AjaxResult.success(map);
    }

    @ApiOperation(value = "获取头像信息接口", notes = "获取头像信息")
    @RequestMapping(value = "getAvatarDetail", method = RequestMethod.POST)
    public AjaxResult<Object> getAvatarDetail(HttpServletRequest request) {
        try {

            JSONObject params = JSON.parseObject(Tools.getBody(request));
            String userId = params.getString("userId");

            if (StringUtils.isEmpty(userId)){
                return AjaxResult.fail("userId不能为空");
            }

            User user = userService.getUserDetail(userId);

            if (Objects.isNull(user)){
                return AjaxResult.fail("未查到用户信息");
            }

            UserAvatar userAvatar = Tools.copyProperties(user, UserAvatar.class);
            return AjaxResult.success(userAvatar);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @ApiOperation(value = "创建群组接口", notes = "创建群组")
    @RequestMapping(value = "createVoiceIntercomGroup", method = RequestMethod.POST)
    public AjaxResult<Object> createVoiceIntercomGroup(HttpServletRequest request) {
        try {
            String uid = LoginUtils.getUser().getUid();

            String groupnum = UUID.randomUUID().toString();

            JSONObject params = JSON.parseObject(Tools.getBody(request));
            String ids = params.getString("ids");

            // 返回新增的人员信息
            List<UserAvatar> userAvatars = new ArrayList<>();
            Map<String, User> userMap = userService.getUserMap();

            List<String> strings = Arrays.asList(ids.split(","));
            strings.forEach(t->{
                VoiceIntercomGroup voiceIntercomGroup = new VoiceIntercomGroup();
                voiceIntercomGroup.setGroupnum(groupnum);
                voiceIntercomGroup.setGroupname("临时组");
                voiceIntercomGroup.setUserid(t);
                voiceIntercomGroup.setCreaterid(uid);
                voiceIntercomGroup.setCreatetime(new Date());
                voiceIntercomGroupMapper.insert(voiceIntercomGroup);

                UserAvatar userAvatar = new UserAvatar();
                User user = userMap.get(t);
                if (Objects.nonNull(user)){
                    userAvatar = Tools.copyProperties(user, UserAvatar.class);
                    userAvatar.setUserId(t);
                    userAvatar.setGroupnum(groupnum);
                    userAvatar.setGroupname(voiceIntercomGroup.getGroupname());
                    userAvatars.add(userAvatar);
                }
            });

            return AjaxResult.success(userAvatars);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @ApiOperation(value = "查询群组接口", notes = "查询群组")
    @RequestMapping(value = "getVoiceIntercomGroup", method = RequestMethod.POST)
    public AjaxResult<Object> getVoiceIntercomGroup(HttpServletRequest request) {
        try {
            String uid = LoginUtils.getUser().getUid();

            JSONObject params = JSON.parseObject(Tools.getBody(request));
            String groupnum = params.getString("groupnum");

            QueryWrapper<VoiceIntercomGroup> voiceIntercomGroupQueryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(groupnum)){
                voiceIntercomGroupQueryWrapper.lambda().eq(VoiceIntercomGroup::getGroupnum, groupnum);
            } else {
                voiceIntercomGroupQueryWrapper.lambda().eq(VoiceIntercomGroup::getCreaterid, uid);
            }

            Map<String, User> userMap = userService.getUserMap();

            List<UserAvatar> userAvatars = new ArrayList<>();
            List<VoiceIntercomGroup> voiceIntercomGroups = voiceIntercomGroupMapper.selectList(voiceIntercomGroupQueryWrapper);
            voiceIntercomGroups.forEach(t->{
                User user = userMap.get(t.getUserid());
                UserAvatar userAvatar = new UserAvatar();
                if (Objects.nonNull(user)){
                    userAvatar = Tools.copyProperties(user, UserAvatar.class);
                    userAvatar.setUserId(t.getUserid());
                    userAvatar.setGroupname(String.valueOf(t.getGroupname()));
                    userAvatar.setGroupnum(String.valueOf(t.getGroupnum()));
                }
                userAvatars.add(userAvatar);
            });

            if (StringUtils.isNotEmpty(groupnum)){
                return AjaxResult.success(userAvatars);
            }

            Map<String, List<UserAvatar>> userAvatarMap = userAvatars.stream().filter(userAvatar -> StringUtils.isNotEmpty(userAvatar.getGroupnum()) ).collect(Collectors.groupingBy(UserAvatar::getGroupnum));
            // 转list
            List<Object> list = new ArrayList<>();
            userAvatarMap.keySet().forEach(t->{
                list.add(userAvatarMap.get(t));
            });

            return AjaxResult.success(list);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @ApiOperation(value = "群组新增成员接口", notes = "群组新增成员")
    @RequestMapping(value = "addIntercomUser", method = RequestMethod.POST)
    public AjaxResult<Object> addIntercomUser(HttpServletRequest request) {
        try {
            String uid = LoginUtils.getUser().getUid();

            JSONObject params = JSON.parseObject(Tools.getBody(request));
            String groupnum = params.getString("groupnum");
            String ids = params.getString("ids");

            if (StringUtils.isEmpty(groupnum)){
                return AjaxResult.fail("群组房间号不能为空");
            }
            if (StringUtils.isEmpty(ids)){
                return AjaxResult.fail("用户ids不能为空");
            }

            List<String> strings = Arrays.asList(ids.split(","));

            // 返回新增的人员信息
            List<UserAvatar> userAvatars = new ArrayList<>();
            Map<String, User> userMap = userService.getUserMap();

            QueryWrapper<VoiceIntercomGroup> voiceIntercomGroupQueryWrapper = new QueryWrapper<>();
            voiceIntercomGroupQueryWrapper.lambda().eq(VoiceIntercomGroup::getGroupnum, groupnum);

            List<VoiceIntercomGroup> voiceIntercomGroups1 = voiceIntercomGroupMapper.selectList(voiceIntercomGroupQueryWrapper);
            //群组名称
            String groupname = "";
            if (Objects.nonNull(voiceIntercomGroups1) && voiceIntercomGroups1.size() > 0){
                groupname = voiceIntercomGroups1.get(0).getGroupname();
            }

            for (String t: strings) {
                voiceIntercomGroupQueryWrapper.lambda().eq(VoiceIntercomGroup::getUserid, t);
                voiceIntercomGroupQueryWrapper.lambda().last(" limit 1");
                VoiceIntercomGroup voiceIntercomGroups = voiceIntercomGroupMapper.selectOne(voiceIntercomGroupQueryWrapper);

                if (Objects.isNull(voiceIntercomGroups)){
                    VoiceIntercomGroup voiceIntercomGroup = new VoiceIntercomGroup();
                    voiceIntercomGroup.setGroupnum(groupnum);
                    voiceIntercomGroup.setGroupname(groupname);
                    voiceIntercomGroup.setUserid(t);
                    voiceIntercomGroup.setCreaterid(uid);
                    voiceIntercomGroup.setCreatetime(new Date());
                    voiceIntercomGroupMapper.insert(voiceIntercomGroup);

                    UserAvatar userAvatar = new UserAvatar();
                    User user = userMap.get(t);
                    if (Objects.nonNull(user)){
                        userAvatar = Tools.copyProperties(user, UserAvatar.class);
                        userAvatar.setUserId(t);
                        userAvatar.setGroupnum(groupnum);
                        userAvatar.setGroupname(voiceIntercomGroup.getGroupname());
                        userAvatars.add(userAvatar);
                    }
                }
            };

            return AjaxResult.success(userAvatars);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @ApiOperation(value = "群组移除成员接口", notes = "群组移除成员")
    @RequestMapping(value = "delIntercomUser", method = RequestMethod.POST)
    public AjaxResult<Object> delIntercomUser(HttpServletRequest request) {
        try {
            String uid = LoginUtils.getUser().getUid();

            JSONObject params = JSON.parseObject(Tools.getBody(request));
            String groupnum = params.getString("groupnum");
            String ids = params.getString("ids");

            if (StringUtils.isEmpty(groupnum)){
                return AjaxResult.fail("群组房间号不能为空");
            }
            if (StringUtils.isEmpty(ids)){
                return AjaxResult.fail("用户ids不能为空");
            }

            List<String> strings = Arrays.asList(ids.split(","));

            strings.forEach(t->{
                QueryWrapper<VoiceIntercomGroup> voiceIntercomGroupQueryWrapper = new QueryWrapper<>();
                voiceIntercomGroupQueryWrapper.lambda().eq(VoiceIntercomGroup::getGroupnum, groupnum);
                voiceIntercomGroupQueryWrapper.lambda().eq(VoiceIntercomGroup::getUserid, t);
                voiceIntercomGroupQueryWrapper.lambda().last(" limit 1");
                VoiceIntercomGroup voiceIntercomGroups = voiceIntercomGroupMapper.selectOne(voiceIntercomGroupQueryWrapper);

                if (Objects.nonNull(voiceIntercomGroups)){
                    QueryWrapper<VoiceIntercomGroup> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(VoiceIntercomGroup::getGroupnum, groupnum);
                    queryWrapper.lambda().eq(VoiceIntercomGroup::getUserid, t);
                    queryWrapper.lambda().eq(VoiceIntercomGroup::getCreaterid, uid);
                    voiceIntercomGroupMapper.delete(queryWrapper);
                }
            });

            return AjaxResult.success();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @ApiOperation(value = "查询群组成员接口", notes = "查询群组成员")
    @RequestMapping(value = "selectIntercomUser", method = RequestMethod.POST)
    public AjaxResult<Object> selectIntercomUser(HttpServletRequest request) {
        try {
            String uid = LoginUtils.getUser().getUid();

            JSONObject params = JSON.parseObject(Tools.getBody(request));
            String name = params.getString("name");

            QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>();
            objectQueryWrapper.lambda().like(User::getName, name);
            List<User> users = userMapper.selectList(objectQueryWrapper);

            List<VoiceIntercomGroup> voiceIntercomGroupList = new ArrayList<>();

            users.forEach(t->{
                QueryWrapper<VoiceIntercomGroup> voiceIntercomGroupQueryWrapper = new QueryWrapper<>();
                voiceIntercomGroupQueryWrapper.lambda().eq(VoiceIntercomGroup::getUserid, t);
                voiceIntercomGroupQueryWrapper.lambda().eq(VoiceIntercomGroup::getCreaterid, uid);
                voiceIntercomGroupQueryWrapper.lambda().last(" limit 1");
                VoiceIntercomGroup voiceIntercomGroup = voiceIntercomGroupMapper.selectOne(voiceIntercomGroupQueryWrapper);
                voiceIntercomGroupList.add(voiceIntercomGroup);
            });

            List<VoiceIntercomGroup> resultVoiceIntercomGroupList = new ArrayList<>();
            Map<String, List<VoiceIntercomGroup>> voiceIntercomGroupMap = voiceIntercomGroupList.stream().collect(Collectors.groupingBy(VoiceIntercomGroup::getGroupnum));
            voiceIntercomGroupMap.keySet().forEach(t->{
                QueryWrapper<VoiceIntercomGroup> voiceIntercomGroupQueryWrapper = new QueryWrapper<>();
                voiceIntercomGroupQueryWrapper.lambda().eq(VoiceIntercomGroup::getGroupnum, t);
                voiceIntercomGroupQueryWrapper.lambda().eq(VoiceIntercomGroup::getCreaterid, uid);
                List<VoiceIntercomGroup> voiceIntercomGroups = voiceIntercomGroupMapper.selectList(voiceIntercomGroupQueryWrapper);
                voiceIntercomGroups.forEach(y->{
                    resultVoiceIntercomGroupList.add(y);
                });
            });

            Map<String, User> userMap = userService.getUserMap();

            List<UserAvatar> userAvatars = new ArrayList<>();
            resultVoiceIntercomGroupList.forEach(t->{
                User user = userMap.get(t.getUserid());
                UserAvatar userAvatar = new UserAvatar();
                if (Objects.nonNull(user)){
                    userAvatar = Tools.copyProperties(user, UserAvatar.class);
                    userAvatar.setUserId(t.getUserid());
                    userAvatar.setGroupname(String.valueOf(t.getGroupname()));
                    userAvatar.setGroupnum(String.valueOf(t.getGroupnum()));
                }
                userAvatars.add(userAvatar);
            });

            Map<String, List<UserAvatar>> userAvatarMap = userAvatars.stream().filter(userAvatar -> StringUtils.isNotEmpty(userAvatar.getGroupnum()) ).collect(Collectors.groupingBy(UserAvatar::getGroupnum));
            // 转list
            List<Object> list = new ArrayList<>();
            userAvatarMap.keySet().forEach(t->{
                list.add(userAvatarMap.get(t));
            });

            return AjaxResult.success(list);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @ApiOperation(value = "编辑群组接口", notes = "编辑群组")
    @RequestMapping(value = "editGroup", method = RequestMethod.POST)
    public AjaxResult<Object> editGroup(HttpServletRequest request) {
        try {
            String uid = LoginUtils.getUser().getUid();

            JSONObject params = JSON.parseObject(Tools.getBody(request));
            String groupnum = params.getString("groupnum");
            String name = params.getString("name");
            String lastcalltime = params.getString("lastcalltime");

            VoiceIntercomGroup voiceIntercomGroup = new VoiceIntercomGroup();
            if (StringUtils.isNotEmpty(name)){
                voiceIntercomGroup.setGroupname(name);
            }
            if (StringUtils.isNotEmpty(lastcalltime)){
                voiceIntercomGroup.setLastcalltime(DateUtil.parseDateTime(lastcalltime));
            }

            QueryWrapper<VoiceIntercomGroup> voiceIntercomGroupQueryWrapper = new QueryWrapper<>();
            voiceIntercomGroupQueryWrapper.lambda().eq(VoiceIntercomGroup::getGroupnum, groupnum);
            voiceIntercomGroupQueryWrapper.lambda().eq(VoiceIntercomGroup::getCreaterid, uid);
            voiceIntercomGroupMapper.update(voiceIntercomGroup, voiceIntercomGroupQueryWrapper);

            return AjaxResult.success();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

}

